package findReplaceString;

import java.util.Arrays;
import java.util.Comparator;

public class Solution {
    class Node{
        int index;
        String source;

        String target;

        public Node(int index,String source,String target){
            this.index = index;
            this.source = source;
            this.target = target;
        }
    }
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            sb.append(s.charAt(i));
        }
        Node[] nodes = new Node[sources.length];
        for (int i = 0; i < indices.length; i++) {
            nodes[i] = new Node(indices[i],sources[i],targets[i]);
        }
        Arrays.sort(nodes, (o1, o2) -> o1.index - o2.index);
        for (int i = 0; i < nodes.length; i++) {
            System.out.println(nodes[i].index);
        }

        int offest = 0; // 偏移量
        for (Node n: nodes) {
            if(check(s,n.index,n.source)){
                int startIndex = n.index + offest;
                int endIndex = startIndex + n.source.length();
                sb.replace(startIndex,endIndex,n.target);
                offest+=n.target.length();
            }
        }
        return sb.toString();
    }
    private boolean check(String s,int index,String source){
        int i;
        for (i = index; i < source.length()&&i<s.length() ; i++) {
            if(s.charAt(i)!=source.charAt(i-index)){
                return false;
            }
            System.out.println(s.charAt(i)+" "+source.charAt(i-index));
        }
        return i==source.length();
    }
}
